package com.gph.saviorframework.wf.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gph.saviorframework.Constants;
import com.gph.saviorframework.util.DateUtils;
import com.gph.saviorframework.wf.service.ActivitiModelService;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by root on 16-7-8.
 */
public class ActivitiModelServiceImpl implements ActivitiModelService {

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 创建流程模型
     *
     * @param name        模型名称
     * @param key         模型key
     * @param description 模型描述
     * @return
     * @throws UnsupportedEncodingException
     */
    public Model createModel(String name, String key, String description) throws UnsupportedEncodingException {
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode modelObjectNode = objectMapper.createObjectNode();
        modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION,
                org.apache.commons.lang.StringUtils.defaultString(description));

        Model newModel = repositoryService.newModel();
        newModel.setMetaInfo(modelObjectNode.toString());
        newModel.setName(name);
        newModel.setKey(key);
        repositoryService.saveModel(newModel);

        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.put("stencilset", stencilSetNode);

        repositoryService.addModelEditorSource(newModel.getId(), editorNode
                .toString().getBytes("utf-8"));

        return newModel;
    }

    /**
     * 复制流程模型
     *
     * @param sourceModelId
     * @param newModelName
     * @param newKey
     * @param newModelDescription
     * @return
     * @throws UnsupportedEncodingException
     */
    public Model copyModel(String sourceModelId, String newModelName, String newKey,String newModelDescription) throws UnsupportedEncodingException {
        if(StringUtils.isEmpty(newModelName)){
            return null;
        }
        Model newModel = repositoryService.newModel();

        ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
        modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, newModelName);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION,
                org.apache.commons.lang.StringUtils.defaultString(newModelDescription));

        newModel.setMetaInfo(modelObjectNode.toString());
        newModel.setName(newModelName);
        newModel.setKey(newKey);

        repositoryService.saveModel(newModel);

        repositoryService.addModelEditorSource(newModel.getId(), repositoryService.getModelEditorSource(sourceModelId));
        repositoryService.addModelEditorSourceExtra(newModel.getId(), repositoryService.getModelEditorSourceExtra(sourceModelId));

        return newModel;
    }

    /**
     * 查询model的map结果，给jqgrid专用的接口
     *
     * @param start
     * @param limit
     * @param dir
     * @return
     */
    public Map<String, Object> findModelsMap(Integer start, Integer limit, String dir) {
        Map<String,Object> map = new HashMap<String, Object>();

        List<Model> list = findModels(start, limit, dir);

        List<Map<String, Object>> models = new ArrayList<Map<String, Object>>();
        for(Model model : list) {
            Map<String, Object> temp = new HashMap<String, Object>();
            temp.put("id", model.getId());
            temp.put("key", model.getKey());
            temp.put("name", model.getName());
            temp.put("deploymentId", model.getDeploymentId());
            temp.put("lastUpdateTime", DateUtils.dateToString(model.getLastUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
            temp.put("version", model.getVersion());
            temp.put("createTime", DateUtils.dateToString(model.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            models.add(temp);
        }

        long records = countAllModel();
        long total = 0;

        if(records%limit==0){
            total = records/limit;
        }
        else{
            total = records/limit + 1;
        }

        map.put(Constants.DEFAULT_RECORD_MODEL_KEY, models);
        map.put(Constants.DEFAULT_COUNT_MODEL_KEY, total);//总页数
        map.put(Constants.DEFAULT_RECORDS_MODEL_KEY,records);//总记录数目
        map.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);

        return map;
    }

    /**
     * 查找所有的模型数量
     *
     * @return
     */
    public long countAllModel() {
        return repositoryService.createModelQuery().count();
    }

    /**
     * 查询所有model
     *
     * @return
     */
    public List<Model> findModels() {
        ModelQuery query = repositoryService.createModelQuery();
        return query.list();
    }

    /**
     * 分页查询model
     *
     * @param start
     * @param limit
     * @return
     */
    public List<Model> findModels(Integer start, Integer limit) {
        ModelQuery query = repositoryService.createModelQuery();
        if(start != null && limit != null) {
            return query.listPage(start, limit);
        }
        return query.list();
    }

    /**
     * 分页查询model。并排序
     *
     * @param start
     * @param limit
     * @param dir
     * @return
     */
    public List<Model> findModels(Integer start, Integer limit, String dir) {
        ModelQuery query = repositoryService.createModelQuery().orderByLastUpdateTime();
        if(dir.toLowerCase().equals(Constants.DEFAULT_SORT_DIRECTION)) {
            query = query.asc();
        } else {
            query = query.desc();
        }
        if(start != null && limit != null) {
            return query.listPage(start, limit);
        }
        return query.list();
    }

    /**
     * 根据模型编号删除模型
     *
     * @param modelId
     */
    public void deleteModelById(String modelId) {
        repositoryService.deleteModel(modelId);
    }

    /**
     * 部署模型
     *
     * @param modelId
     */
    public boolean deployModelById(String modelId) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));

            byte[] bpmnBytes = null;
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName())
                    .addString(processName, new String(bpmnBytes)).deploy();

            if (deployment != null && deployment.getId() != null) {
                return true;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
